package cn.yitun.chat.yitunservermanagecore.general.manage.core.controller;

import cn.yitun.chat.yituncommonmessage.ExceptionEnum;
import cn.yitun.chat.yituncommonmessage.YitunException;
import cn.yitun.chat.yituncommonmessage.result.ResultMessage;
import cn.yitun.chat.yituncommonutil.YitunMD5Util;
import cn.yitun.chat.yituncommonutil.YitunStringUtil;
import cn.yitun.chat.yitungeneral.annotation.codec.Encryped;
import cn.yitun.chat.yitungeneral.annotation.parameter.JsonDefine;
import cn.yitun.chat.yitungeneral.annotation.parameter.ParamDefine;
import cn.yitun.chat.yitungeneral.annotation.parameter.RequestParameter;
import cn.yitun.chat.yitunservercommonlib.annotation.Log;
import cn.yitun.chat.yitunservercommonlib.basebean.web.JwtUserDto;
import cn.yitun.chat.yitunservercommonlib.crud.yitun.BaseController;
import cn.yitun.chat.yitunservercommonlib.dataentity.dto.system.user.ResetPwdDto;
import cn.yitun.chat.yitunservercommonlib.dataentity.dto.system.user.UserDto;
import cn.yitun.chat.yitunservercommonlib.dataentity.po.system.user.UserInfo;
import cn.yitun.chat.yitunservercommonlib.dataentity.vo.system.user.UserVo;
import cn.yitun.chat.yitunservercommonlib.enums.system.UserRoleTypeEnums;
import cn.yitun.chat.yitunservermanagecore.general.bridge.auth.annotation.PermissionMapping;
import cn.yitun.chat.yitunservermanagecore.general.manage.system.service.MenuService;
import cn.yitun.chat.yitunservermanagecore.general.manage.system.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 
 * date 2018-07-19 09:29:16<br>
 * description 系统用户管理
 * @author yitun<br>
 * @since
 */
@RestController
@RequestMapping("/manage/core")
public class UserController extends BaseController{
	@Resource
	private UserService userService;

	@Resource
	private MenuService menuService;

	@RequestParameter
	@PermissionMapping(name = "获取当前用户信息", perms = "sys:user:info")
	@GetMapping("/user/currentUser")
	public ResultMessage user(JwtUserDto jwtUserDto) {
		ResultMessage rm = new ResultMessage();
		rm.bodyPut("user",userService.getVo(jwtUserDto.getUserId()));
		rm.bodyPut("permList", menuService.selPermList(jwtUserDto.getUserId()));
		return rm ;
	}

	@RequestParameter
	@PermissionMapping(name = "用户列表", perms = "sys:user:user")
	@PostMapping("/user/page")
//	@DataScope(tableAlias = "d")
	Object page(JwtUserDto jwtUserDto, @JsonDefine UserDto userDto ) {
		//查询列表数据
		checkRootPage(userDto , jwtUserDto);
//		JwtUserDto jwtUserDto = getCurrentLoginUser();
//		userDto.setDataScope(DataScopeAspect.companyFilter(userService.getFullUser(jwtUserDto.getUserId() , jwtUserDto.getCompanyId()) , "a"));
//		UserServiceImpl.dealDept(userDto);
		PageHelper.startPage(userDto.getCurrentPageNo() , userDto.getPageSize());
		List<UserVo> userVos = userService.listVO(userDto);
		ResultMessage rm = new ResultMessage();
		rm.bodyPut("page", new PageInfo<>(userVos));
		return rm;
	}

	@Log("用户新增")
	@RequestParameter
	@PermissionMapping(name = "用户新增", perms = "sys:user:update")
	@PostMapping("/user/save")
	@Encryped(decode = true)
	public ResultMessage save(JwtUserDto jwtUserDto, @JsonDefine UserDto user) {
		setUserMsgSave(user, jwtUserDto);
		user.setPassword(YitunMD5Util.md5L32(user.getPassword()));
		int code = userService.save(user) ;
		if (code == 0)
			throw new YitunException(ExceptionEnum.ADD_FAIL);
		else if(code == -1)
			throw new YitunException(ExceptionEnum.COMPANY_EXISTS_CHIEF);

		return new ResultMessage();
	}

	@Log("用户编辑")
	@RequestParameter
	@PermissionMapping(name = "用户编辑", perms = "sys:user:update")
	@PutMapping("/user/update")
	@Encryped(decode = true)
	public Object update(JwtUserDto jwtUserDto, @JsonDefine UserDto user) {
		setUserMsgUpdate(user, jwtUserDto);
		if (userService.update(user) == 0)
			throw new YitunException(ExceptionEnum.EDIT_FAIL);

		return new ResultMessage();
	}
	@Log("用户删除")
	@RequestParameter
	@PermissionMapping(name = "用户删除", perms = "sys:user:remove")
	@DeleteMapping("/user/remove/{userId}")
	public Object remove( @PathVariable Long userId) {
		if (userService.remove(userId) == 0)
			throw new YitunException(ExceptionEnum.DELETE_FAILED);

		return new ResultMessage();
	}

	@Log("用户批量删除")
	@RequestParameter
	@PermissionMapping(name = "用户批量删除", perms = "sys:user:remove")
	@DeleteMapping("/user/batchRemove/{ids}")
	public Object batchRemove( @PathVariable Long[] userIds) {
		if (userService.batchRemove(userIds) == 0)
			throw new YitunException(ExceptionEnum.DELETE_FAILED);
		return new ResultMessage();
	}

	@Log("用户修改密码")
	@RequestParameter
	@PermissionMapping(name = "用户修改密码", perms = "sys:user:update")
	@PostMapping("/user/resetPwd")
	@Encryped(decode = true)
	public Object resetPwd(JwtUserDto jwtUserDto, @JsonDefine ResetPwdDto resetPwdDto) {
		if (userService.resetPwd(resetPwdDto , userService.get(jwtUserDto.getUserId())) == 0)
			throw new YitunException(ExceptionEnum.UPDATE_PASSWORD_FAILED);
		return new ResultMessage();
	}

	@Log("管理员修改用户密码")
	@RequestParameter
	@PermissionMapping(name = "管理员修改用户密码", perms = "sys:user:update")
	@PostMapping("/user/adminResetPwd")
	@Encryped(decode = true)
	public Object  adminResetPwd(JwtUserDto jwtUserDto, @JsonDefine ResetPwdDto resetPwdDto) {
		if(YitunStringUtil.isEmpty(resetPwdDto.getNewPassword()))
				throw new YitunException(ExceptionEnum.USERNAME_OR_PASSWORD_ERROR);

		if(YitunStringUtil.isEmpty(resetPwdDto.getComfirnNewPwd()))
			throw new YitunException(ExceptionEnum.USERNAME_OR_PASSWORD_ERROR);

		if(!resetPwdDto.getNewPassword().equals(resetPwdDto.getComfirnNewPwd()))
			throw new YitunException(ExceptionEnum.USERNAME_OR_PASSWORD_ERROR);

		if (userService.adminResetPwd(resetPwdDto) == 0 )
			throw new YitunException(ExceptionEnum.UPDATE_PASSWORD_FAILED);

		return new ResultMessage();
	}

	@RequestParameter
	@PermissionMapping(name = "获取用户", perms = "sys:user:info")
	@RequestMapping(method = RequestMethod.POST, value = "/user/get")
	public Object get(HttpServletRequest request,
			@ParamDefine("id") Long id) {
		ResultMessage rm = new ResultMessage();
		try {
			UserInfo user = userService.getById(id);
			rm.bodyPut("user", user);
		} catch (Exception e) {
			e.printStackTrace();
			rm.addError("500", "系统异常");
		}
		return rm;
	}

	@RequestParameter
	@PermissionMapping(name = "账号是否存在", perms = "sys:user:exist")
	@RequestMapping(method = RequestMethod.POST, value = "/user/isExist")
	public Object isExistAccount(
			HttpServletRequest request,
			@ParamDefine("id") Long id,
			@ParamDefine("account") String account) {
		ResultMessage rm = new ResultMessage();
		boolean isExist = userService.isExistAccount(account, id);
		rm.bodyPut("exist", isExist);
		return rm;
	}

	@RequestParameter
	@PermissionMapping(name = "获取用户详情",  perms = "sys:user:info")
	@RequestMapping(method = RequestMethod.POST, value = "/user/getInfo")
	public Object loadInfo(
			HttpServletRequest request,
			@ParamDefine("id") Long id) {
		ResultMessage rm = new ResultMessage();
		try {
			UserInfo user = userService.getById(id);
			rm.bodyPut("user", user);
		} catch (Exception e) {
			e.printStackTrace();
			rm.addError("500", "系统异常");
		}
		return rm;
	}

	@RequestParameter
	@PermissionMapping(name = "修改密码", perms = "sys:user:update")
	@RequestMapping(method = RequestMethod.POST, value = "/user/updatePassword")
	@Encryped(decode = true)
	public Object saveUpdatePassword(ModelMap map,
			@ParamDefine("id") Long userId,
			@ParamDefine("password") String password) {
		ResultMessage rm = new ResultMessage();
		try {
			String text = "";
			int mark = 1;
			if (null == password || "".equals(password)) {
				text = ("密码不能为空！");
				mark = 0;
			}
			if (mark > 0){
				mark = userService.updatePassword(userId, password);
				if (mark > 0) {
					text = ("修改成功！");
				} else {
					text = ("修改失败！");
				}
			}
			if (mark == 0) {
				rm.addWarning("001", text);
			}
		} catch (Exception e) {
			e.printStackTrace();
			rm.addError("500", "系统异常");
		}
		return rm;
	}
	
	
	@RequestParameter
	@PermissionMapping(name = "设为管理员",  perms = "sys:user:update")
	@RequestMapping(method = RequestMethod.POST, value = "/user/toAdmin")
	public Object toAdmin(ModelMap map,
			@ParamDefine("id") Long userId,
			@ParamDefine("type") String type) {
		ResultMessage rm = new ResultMessage();
		try {
			String text = "";
			int mark = userService.updateType(userId, UserRoleTypeEnums.TYPE_ADMIN.getType());
			if (mark > 0) {
				text = ("修改成功！");
			} else {
				text = ("修改失败！");
			}
			if (mark == 0) {
				rm.addWarning("001", text);
			}
		} catch (Exception e) {
			e.printStackTrace();
			rm.addError("500", "系统异常");
		}
		return rm;
	}
}
